<template>
  <div style="max-width: 960px; margin: 16px auto; padding: 0 12px;">
    <a-card title="用户角色绑定">
      <a-space style="margin-bottom:12px; flex-wrap: wrap;" :size="'small'">
        <a-input-number v-model:value="userId" :min="1" placeholder="用户ID" />
        <a-input v-model:value="keyword" placeholder="按角色编码/名称筛选" style="width: 240px" />
        <a-button type="primary" @click="loadAll">加载角色与当前绑定</a-button>
        <a-button type="primary" @click="save" :disabled="!userId">保存绑定</a-button>
      </a-space>
      <a-table :data-source="roles" :columns="columns" row-key="id" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key==='bind'">
            <a-checkbox v-model:checked="checkedMap[record.id]" />
          </template>
        </template>
      </a-table>
    </a-card>
    <a-drawer v-model:open="userDrawer" title="搜索用户" width="520">
      <a-space style="margin-bottom: 12px">
        <a-input v-model:value="uq" placeholder="用户名/昵称/邮箱" allow-clear style="width: 260px" />
        <a-button type="primary" @click="loadUsers(1)">搜索</a-button>
      </a-space>
      <a-list :data-source="userList" :pagination="{current: upageNo, pageSize: upageSize, total: utotal, onChange: loadUsers}" bordered>
        <template #renderItem="{ item }">
          <a-list-item @click="selectUser(item)" style="cursor:pointer">
            <a-avatar :src="(item as any).avatar" />
            <div style="margin-left:8px">
              <div>{{ (item as any).username }} <span class="muted">{{ (item as any).nickname }}</span></div>
              <div class="muted">{{ (item as any).email }}</div>
            </div>
          </a-list-item>
        </template>
      </a-list>
    </a-drawer>
  </div>
  
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { listRoles, getUserRoleIds, setUserRoleIds, pageUsers, type RoleVO, type UserBrief } from '@/api/admin/modules/system'

const userId = ref<number | null>(null)
const keyword = ref('')
const roles = ref<RoleVO[]>([])
const checkedMap = ref<Record<number, boolean>>({})
// 用户搜索抽屉
const userDrawer = ref(false)
const uq = ref('')
const upageNo = ref(1)
const upageSize = ref(10)
const utotal = ref(0)
const userList = ref<UserBrief[]>([])

function selectUser(u: UserBrief) {
  userId.value = u.id
  userDrawer.value = false
}

async function loadUsers(p?: number) {
  if (p) upageNo.value = p
  const resp = await pageUsers(uq.value || undefined, upageNo.value, upageSize.value)
  if (resp.code === 0) {
    utotal.value = resp.data.total
    userList.value = resp.data.records
  }
}

const columns = computed(() => [
  { title: '绑定', key: 'bind' },
  { title: '角色编码', dataIndex: 'code' },
  { title: '角色名称', dataIndex: 'name' },
  { title: '数据范围', dataIndex: 'dataScope' }
])

async function loadAll() {
  const [r, ur] = await Promise.all([
    listRoles(keyword.value || undefined),
    userId.value ? getUserRoleIds(userId.value) : Promise.resolve({ code: -1, data: [] } as any)
  ])
  if (r.code === 0) {
    roles.value = r.data
    checkedMap.value = {}
    if (ur.code === 0) {
      for (const id of ur.data) checkedMap.value[id as number] = true
    }
  }
}

async function save() {
  if (!userId.value) { message.warning('请先填写用户ID'); return }
  const roleIds = Object.keys(checkedMap.value).filter(k => checkedMap.value[Number(k)]).map(n => Number(n))
  const resp = await setUserRoleIds(userId.value, roleIds)
  if (resp.code === 0) message.success('已保存')
}

</script>


